using System;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;

namespace Function.HotUpdate
{
    public class HotLightHouse : HotStep
    {
        public override HotState GetHotState()
        {
            return HotState.LightHouse;
        }

        public HotLightHouse(HotContext hotContext, bool cb) : base(hotContext, cb)
        {
        }

        protected override IEnumerator OnExecute()
        {
            if (_restTime > 0)
            {
                yield return new WaitForSeconds(_restTime);
                _restTime = 0;
            }

            if (Application.internetReachability == NetworkReachability.NotReachable) //第一个阶段处理一下 没用网络的状态
            {
                _hotContext.Error("network is closed", "network connect fair", (int)HotUpdateErrorType.NotReachable);
                SetSuccess(false);
                yield break;
            }

            bool initAddressableResult = false;
            yield return HotManager.InitAddressableWithTimeout(15f, b => { initAddressableResult = b; });
            if (!initAddressableResult)
            {
                _hotContext.Error("Addressables.InitializeAsync", "failed",
                    (int)HotUpdateErrorType.FetchLighthouse_InitializeAsync);
                // 切换cdn
                // CdnSelector.Roll();
                SetSuccess(false);
                yield break;
            }

            _hotContext.Info("HotLightHouse", "Start");
            string error = "";
            var lighthouseUrl = _hotContext.GetLightHouseURL();
            var startTime = Time.unscaledTime;
            yield return Lighthouse.NewFromUrl(lighthouseUrl,
                (lighthouse, errStr) =>
                {
                    error = errStr;
                    if (lighthouse != null)
                    {
                        _hotContext._lighthouse = lighthouse;
                    }
                });

            var costTime = Time.unscaledTime - startTime;
            HotManager.Instance._commonTrace?.Invoke("hotfix_lighthouse", new Dictionary<string, JsonData>
            {
                { "url", lighthouseUrl },
                { "error", error },
                { "cost", costTime },
                { "success", string.IsNullOrEmpty(error) }
            });

            if (!string.IsNullOrEmpty(error))
            {
                SetSuccess(false);
                _hotContext.Error("LightHouse 访问失败", error, (int)HotUpdateErrorType.FetchLighthouse);
                yield break;
            }

            _hotContext._remoteVersion = new Version(_hotContext.GetRemoteResVersion());
            HotManager.Instance._remoteVersionGet?.Invoke(_hotContext._bootVersion, _hotContext._remoteVersion);
            SetSuccess(true);
            _hotContext.Info("HotLightHouse", "End");
            yield return Finish();
        }

        public override void ResNet()
        {
            _restTime = 2f; //重试流程
            HotManager.Instance.StartCoroutine(Execute());
            base.ResNet();
        }

        public override void StopNet()
        {
            SetSuccess(false);
            HotManager.Instance.StopAllCoroutines();
            base.StopNet();
        }
    }
}